import Link from './components/link.js';
import View from './components/view.js';

class VueRouter {
  static _Vue = null;

  constructor(options) {
    this.mode = options.mode || "hash";
    let initRoute = "hash" === this.mode ? location.hash.substr(1) : location.pathname;
    this.options = options;
    this.data = VueRouter._Vue.observable({
      current: initRoute
    });
    this.routeMap = {};
  }

  static install(Vue) {
    if (VueRouter.install.installed) return;
    VueRouter._Vue = Vue;
    VueRouter.install.installed = true;

    Vue.mixin({
      beforeCreate() {
        if (this.$options.router) {
          // Vue实例执行逻辑
          VueRouter._Vue.prototype.$router = this.$options.router;
          this.$options.router.init();
        } else {
          // Vue组件执行逻辑
        }
      }
    })
  }

  init() {
    this.createRouteMap();
    this.initComponents(VueRouter._Vue);
    this.initEvent();
  }

  createRouteMap() {
    for (const route of this.options.routes || []) {
      const { path, name, component, title = "", meta = {} } = route;
      this.routeMap[path] = { title, meta, component, name };
    }
  }

  initComponents(Vue) {
    Vue.component('router-link', Link);

    Vue.component('router-view', View);
  }

  initEvent() {
    window.addEventListener('popstate', (e) => {
      this.data.current = location.pathname;
    });
    window.addEventListener('hashchange', (e) => {
      this.data.current = location.hash.substr(1);
    });
  }
}

export default VueRouter;
